package fun.coding.leetcode;

import java.util.HashMap;
import java.util.Map;

public class RomanToInteger {

	public static void main(String[] args) {
		RomanToInteger ins = new RomanToInteger();
		System.out.println(ins.romanToInt("DCXXI"));
	}
	
	public int romanToInt(String s) {
		if (s == null || s.isEmpty()) return 0;
		
		Map<Character, Integer> lookup = new HashMap<Character, Integer>();
		lookup.put('I', 1);
		lookup.put('V', 5);
		lookup.put('X', 10);
		lookup.put('L', 50);
		lookup.put('C', 100);
		lookup.put('D', 500);
		lookup.put('M', 1000);
		
		int sum = 0;
		for (int i = 0; i < s.length(); i++) {
			if ((i + 1 < s.length()) && lookup.get(s.charAt(i + 1)) > lookup.get(s.charAt(i))) {
				sum += lookup.get(s.charAt(i+1)) - lookup.get(s.charAt(i));
				i++;
			} else {
				sum += lookup.get(s.charAt(i));
			}
		}
		return sum;
	}
	
	
	/* Here i just look ahead two steps, 
	 * A more clear way is if XLIV (44) 2nd letter is larger, then do a minus. 
     */
    public int romanToIntLookTwoSteps(String s) {
        if (s == null || s.isEmpty()) {
            return 0;
        }
        
        HashMap<String, Integer> map = this.init();
        
        int n = s.length();
        int result = 0;
        
        for (int i = 0; i < n; i++) {
            if ((i + 1) < n && map.containsKey(s.substring(i, i + 2))) {
                result += map.get(s.substring(i, i + 2));
                i++;
            } else {
                // map.get takes in an object, so need to convert the char to string. 
                result += map.get(Character.toString(s.charAt(i)));
            }
        }
        return result;
    }
    
    private HashMap<String, Integer> init() {
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        map.put("M", 1000);
        map.put("CM", 900);
        map.put("D", 500);
        map.put("CD", 400);
        map.put("C", 100);
        map.put("XC", 90);
        map.put("L", 50);
        map.put("XL", 40);
        map.put("X", 10);
        map.put("IX", 9);
        map.put("V", 5);
        map.put("IV", 4);
        map.put("I", 1);
        
        return map;
    }

}
